//
//  MWGoodsDetailsController.m
//  XiRan-iOS
//
//  Created by Richfit on 2019/10/18.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWGoodsDetailsController.h"

#import "MWGoodsDetailsBriefCell.h"
#import "MWGoodsDetailsAttrCell.h"
#import "MWGoodsDetailsAttrHeaderView.h"
#import "MWMessageController.h"


#import "MWShareView.h"

#import "MWGoodsDetailsAttr.h"

#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKShareKit/FBSDKShareKit.h>

@interface MWGoodsDetailsController () <UITableViewDataSource, UITableViewDelegate, FBSDKSharingDelegate, MWWXApiManagerDelegate>
@property (strong, nonatomic) UIButton *collectBtn;
@property (strong, nonatomic) UITableView *tableView;

@property (strong, nonatomic) NSString *shareUrl;
@property (strong, nonatomic) UIImage *shareImage;
@property (strong, nonatomic) MWGoods *goods;

@property (strong, nonatomic) NSString *phone;

@end

@implementation MWGoodsDetailsController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.backgroundColor = [UIColor redColor];
    [self setupPageSubviews];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self loadConfig];
    [self loadGoodsDetails];
    [self loadServicePhone];
}

- (void)collectAction:(UIButton *)sender {
    if (sender.isSelected) {
        [self addCollectWithGoodsId:_productId type:1];
        
    } else {
        [self addCollectWithGoodsId:_productId type:0];
    }
}

- (void)shareAction:(UIButton *)sender {
    if (!_goods) {
        return;
    }
    
    MWShareView *shareView = [[MWShareView alloc] init];
    shareView.block = ^(NSInteger position) {
        if (position == 0) {
            [self shareToWeixinWithType:0];
            
        } else if (position == 1) {
            [self shareToWeixinWithType:1];
            
        } else {
            [self shareToFacebook];
        }
    };
    [shareView show];
}

- (void)shareToWeixinWithType:(NSInteger)type {
    
    [MWWXApiManager sharedManager].delegate = self;
    
    NSString *urlStr;
    if ( [[MWConfigManager manager].language isEqualToString:@"0"]) {
        urlStr =  [NSString stringWithFormat:@"%@id=%ld&lang=zh-cn",_shareUrl, _goods.mid];
    } else if ( [[MWConfigManager manager].language isEqualToString:@"2"]) {
        urlStr =  [NSString stringWithFormat:@"%@id=%ld&lang=japan",_shareUrl, _goods.mid];
    } else {
        urlStr =  [NSString stringWithFormat:@"%@id=%ld&lang=en",_shareUrl, _goods.mid];
    }
    
    WXWebpageObject *webpageObject = [WXWebpageObject object];
    webpageObject.webpageUrl = urlStr;
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = _goods.store_name;
    message.description = _goods.store_name;
    [message setThumbImage:_shareImage];
    message.mediaObject = webpageObject;
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    
    if (type == 0) {
        req.scene = WXSceneSession;
    } else {
        req.scene = WXSceneTimeline;
    }
    
    [WXApi sendReq:req completion:^(BOOL success) {
    }];
}

- (void)managerDidRecvMessageResponse:(SendMessageToWXResp *)response {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeText;
    if (response.errCode == WXErrCodeUserCancel) {
        hud.label.text = [[MWConfigManager manager] objectForKey:@"share_cancle" defaultValue:@"分享取消"];
        
    } else if (response.errCode == WXSuccess){
        hud.label.text = [[MWConfigManager manager] objectForKey:@"share_success" defaultValue:@"分享成功"];
        
    } else {
        hud.label.text = [[MWConfigManager manager] objectForKey:@"share_error" defaultValue:@"分享失败"];
    }
    [hud hideAnimated:YES afterDelay:2];
}

#pragma mark - Facebook Share
- (void)shareToFacebook {
    FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
    NSString *urlStr;
    if ( [[MWConfigManager manager].language isEqualToString:@"0"]) {
        urlStr =  [NSString stringWithFormat:@"%@id=%ld&lang=zh-cn",_shareUrl, _goods.mid];
    } else if ( [[MWConfigManager manager].language isEqualToString:@"2"]) {
        urlStr =  [NSString stringWithFormat:@"%@id=%ld&lang=japan",_shareUrl, _goods.mid];
    } else {
        urlStr =  [NSString stringWithFormat:@"%@id=%ld&lang=en",_shareUrl, _goods.mid];
    }
      
    content.contentURL = [NSURL URLWithString:urlStr];
    content.quote = NSLocalizedString(@"Share_Message", @"分享内容");
    [FBSDKShareDialog showFromViewController:self withContent:content delegate:self];
    FBSDKShareDialog *dialog = [[FBSDKShareDialog alloc] init];
    dialog.shareContent = content;
    dialog.fromViewController = self;
    dialog.delegate = self;
    dialog.mode = FBSDKShareDialogModeNative;
    [dialog show];
}


#pragma mark - FBSDKSharingDelegate
- (void)sharerDidCancel:(id<FBSDKSharing>)sharer {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.label.text = [[MWConfigManager manager] objectForKey:@"share_cancle" defaultValue:@"分享取消"];
    [hud hideAnimated:YES afterDelay:2];
}

- (void)sharer:(id<FBSDKSharing>)sharer didFailWithError:(NSError *)error {
     FBSDKShareDialog *dialog = (FBSDKShareDialog *)sharer;
    if (error == nil && dialog.mode == FBSDKShareDialogModeNative) {
        // 如果使用原生登录失败，但error为空，那是因为用户没有安装Facebook app
        // 重设dialog的mode，再次弹出对话框
        dialog.mode = FBSDKShareDialogModeBrowser;
        [dialog show];
        
    } else if (error != nil) {
        
    } else {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = [[MWConfigManager manager] objectForKey:@"share_error" defaultValue:@"分享失败"];
        [hud hideAnimated:YES afterDelay:2];
    }
}

- (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults:(NSDictionary *)results {
    NSString *postId = results[@"postId"];
    FBSDKShareDialog *dialog = (FBSDKShareDialog *)sharer;
    if (dialog.mode == FBSDKShareDialogModeBrowser && (postId == nil || [postId isEqualToString:@""])) {
        // 如果使用webview分享的，但postId是空的，
        // 这种情况是用户点击了『完成』按钮，并没有真的分享
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = [[MWConfigManager manager] objectForKey:@"share_success" defaultValue:@"分享成功"];
        [hud hideAnimated:YES afterDelay:2];
    } else {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = [[MWConfigManager manager] objectForKey:@"share_success" defaultValue:@"分享成功"];
        [hud hideAnimated:YES afterDelay:2];
    }
}


- (void)updateCollectionState {
    if (_goods) {
        if (_goods.collection == 0) {
            _collectBtn.selected = NO;
        } else {
            _collectBtn.selected = YES;
        }
    }
}

- (void)loadServicePhone {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.label.text = [[MWConfigManager manager] objectForKey:@"loadin" defaultValue:@"加载中..."];

    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:_productId forKey:@"product_id"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kGoodsPhoneUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
//        NSString *msg = [dic objectForKey:@"msg"];
        [hud hideAnimated:YES];
        if (code == 1) {
            weakSelf.phone = [dic objectForKey:@"data"];
            [weakSelf.tableView reloadData];
        }
        
    } failure:^(NSError *error) {
        [hud hideAnimated:YES];
    }];
}

- (void)loadGoodsDetails {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.label.text = [[MWConfigManager manager] objectForKey:@"loadin" defaultValue:@"加载中..."];

    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:_productId forKey:@"product_id"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kGoodsDetailsUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
//        NSString *msg = [dic objectForKey:@"msg"];
        [hud hideAnimated:YES];
        if (code == 1) {
            weakSelf.goods = [MWGoods mj_objectWithKeyValues:[dic objectForKey:@"data"]];
            weakSelf.shareImage = [UIImage getImageFromURL:weakSelf.goods.image];
            [weakSelf updateCollectionState];
            [weakSelf.tableView reloadData];
            
        }
        
    } failure:^(NSError *error) {
        [hud hideAnimated:YES];
    }];
}

- (void)addCollectWithGoodsId:(NSString *)goodsId type:(NSInteger)type {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:_productId forKey:@"product_id"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", type] forKey:@"type"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.label.text = [[MWConfigManager manager] objectForKey:@"loadin" defaultValue:@"加载中..."];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kGoodsCollectUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
//        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        if ([[dataDic objectForKey:@"status"] integerValue] == 1) {
            weakSelf.collectBtn.selected = YES;
        } else {
            weakSelf.collectBtn.selected = NO;
        }
    
        hud.mode = MBProgressHUDModeText;
        hud.label.text = msg;
        [hud hideAnimated:YES afterDelay:2];
        
    } failure:^(NSError *error) {
        hud.mode = MBProgressHUDModeText;
        hud.label.text = @"未知错误";
        [hud hideAnimated:YES afterDelay:2];
    }];
}

- (void)loadConfig {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"isMaterial"];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kConfigUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
//        NSString *msg = [dic objectForKey:@"msg"];
        if (code == 1) {
            NSDictionary *dataDic = [dic objectForKey:@"data"];
            weakSelf.shareUrl = [NSString stringWithFormat:@"%@%@", [dataDic objectForKey:@"domain"], [dataDic objectForKey:@"url"]];
        }
    } failure:^(NSError *error) {
        
    }];
}


#pragma mark - UITableViewDataSource && UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
        
    } else if (section == 1) {
        return 2;
        
    } else {
        if ([MWConfigManager manager].isNetError) {
            self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"click_retry" defaultValue:@"点击重试"];
            self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
            tableView.hidden = YES;
        } else if (!_goods.attr.count) {
            if (self.isFirst) {
                
            } else {
                self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"nodata" defaultValue:@"暂无数据"];
                self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
                tableView.hidden = YES;
            }
            
        } else {
            self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
            tableView.hidden = NO;
        }

        if (_goods) {
            return _goods.attr.count;
        } else {
            return 0;
        }
    }
}


- (void)refresh {
    [super refresh];
    [self loadConfig];
    [self loadGoodsDetails];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.1f;
    } else if (section == 1) {
        return 0.1f;
    }
    return 50.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return [[UIView alloc] initWithFrame:CGRectZero];
        
    } else if (section == 1) {
        return [[UIView alloc] initWithFrame:CGRectZero];
    }
    
    static NSString *identifier = @"MWGoodsDetailsAttrHeaderView";
    MWGoodsDetailsAttrHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identifier];
    if (!header) {
        header = [[MWGoodsDetailsAttrHeaderView alloc] initWithReuseIdentifier:identifier];
    }
    
    header.title = [[MWConfigManager manager] objectForKey:@"specification" defaultValue:@"规格"];
    
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *identifier = @"MWGoodsDetailsBriefCell";
        MWGoodsDetailsBriefCell *briefCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!briefCell) {
            briefCell = [[MWGoodsDetailsBriefCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            briefCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        if (_goods) {
            [briefCell setupData:_goods];
        }
        
        return briefCell;
        
    } else if (indexPath.section == 1) {
        static NSString *identifier = @"MWGoodsDetailsContactCell";
        MWGoodsDetailsAttrCell *contactCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!contactCell) {
            contactCell = [[MWGoodsDetailsAttrCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            contactCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (indexPath.row == 0) {
            contactCell.accessoryType = UITableViewCellAccessoryNone;
            NSString *email = [[MWConfigManager manager] objectForKey:@"email" defaultValue:@"邮箱"];
            contactCell.title = [NSString stringWithFormat:@"%@：%@", email, _phone ? _phone : @""];
        } else {
            contactCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            contactCell.title = [[MWConfigManager manager] objectForKey:@"contact_customer" defaultValue:@"联系客服"];
        }
        
        return contactCell;
    } else {
        static NSString *identifier = @"MWGoodsDetailsAttrCell";
        MWGoodsDetailsAttrCell *attrCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!attrCell) {
            attrCell = [[MWGoodsDetailsAttrCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            attrCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        if (_goods) {
            MWGoodsDetailsAttr *attr = _goods.attr[indexPath.row];
            attrCell.title = [NSString stringWithFormat:@"%@ ：%@", attr.attr_name, attr.attr_value];
        }
        
        return attrCell;
    }    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
//            NSString *phoneStr = [NSString stringWithFormat:@"tel:%@", _phone];
//            if(@available(iOS 10.0, *)) {
//                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneStr] options:@{} completionHandler:nil];
//                
//            } else {
//                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneStr]];
//            }
            
        } else {
            MWMessageController *controller = [[MWMessageController alloc] init];
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
}

- (void)setupPageSubviews {
    if ([MWUserManager manager].user.mid == 2) {
        UIButton *moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        moreBtn.frame = CGRectMake(0, 0, 20, 44);
        [moreBtn setImage:[UIImage imageNamed:@"fenxiang"] forState:UIControlStateNormal];
        UIBarButtonItem *moreButtonItem = [[UIBarButtonItem alloc] initWithCustomView:moreBtn];
        [moreBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItems = @[moreButtonItem];
        
    } else {
        _collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _collectBtn.frame = CGRectMake(0, 0, 30, 44);
        [_collectBtn setImage:[UIImage imageNamed:@"ic_collect_n"] forState:UIControlStateNormal];
        [_collectBtn setImage:[UIImage imageNamed:@"ic_collect_s"] forState:UIControlStateSelected];
        [_collectBtn addTarget:self action:@selector(collectAction:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *collecButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_collectBtn];
        
        UIButton *moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        moreBtn.frame = CGRectMake(0, 0, 20, 44);
        [moreBtn setImage:[UIImage imageNamed:@"ic_more"] forState:UIControlStateNormal];
        UIBarButtonItem *moreButtonItem = [[UIBarButtonItem alloc] initWithCustomView:moreBtn];
        [moreBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItems = @[moreButtonItem, collecButtonItem];
    }
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 300;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

@end
